package com.bentley.kotlindemo.ui.kits.authorlist_paging

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.bentley.kotlindemo.App
import com.bentley.kotlindemo.R
import com.bentley.kotlindemo.base.BaseStateViewActivity
import com.bentley.kotlindemo.databinding.ActivityAuthorPagingBinding
import com.bentley.kotlindemo.ui.widget.status.MultipleStateView
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * <pre>
 *  ┌────────────────────────────────────────────
 *  │ @author  Lee  @date 2021/3/24 18:04
 *  ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
 *  │ @desc 分页加载数据演示
 *  └────────────────────────────────────────────
 * </pre>
 */
class AuthorPagingActivity : BaseStateViewActivity<ActivityAuthorPagingBinding, AuthorPagingModel>(){

    lateinit var mainListAdapter: AuthorPagingAdapter

    override fun initView(savedInstanceState: Bundle?) {
        setAdapter()
        setupView()
    }

    override fun getLayoutId() = R.layout.activity_author_paging

    fun setAdapter(){
        mainListAdapter = AuthorPagingAdapter()
        dataBinding.recyclerview.apply {
            layoutManager = LinearLayoutManager(App.INSTANCE)
            adapter = mainListAdapter
        }


        //这是分页adapter的独有状态监听
        mainListAdapter.addLoadStateListener {
            when(it.refresh){
                is LoadState.Loading ->{
                    showLoadingView()
                }

                is LoadState.NotLoading ->{
                    showContent()
                }

                is LoadState.Error ->{
                   showNetError()
                }

            }
        }

    }

    private fun setupView() {
        lifecycleScope.launch {
            viewModel.getArticleData().collectLatest {
                mainListAdapter.submitData(it)
            }
        }

        viewModel.name.observe(this, Observer {
            dataBinding.tvName.text=it
        })
    }

    override fun getMultipleStateView(): MultipleStateView = dataBinding.multipleStateView

    override fun onDestroy() {
        super.onDestroy()
        Log.e("AuthorPagingActivity","onDestroy销毁")
    }

}